package org.jaaksi.plugin.trace

import com.android.build.gradle.AppPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project

class TracePlugin implements Plugin<Project> {

  @Override
  void apply(Project project) {
    System.out.println("------------------开始----------------------");
    System.out.println("这是我们的自定义插件!");
    //AppExtension就是build.gradle中android{...}这一块
    //    def android = project.extensions.getByType(AppExtension)
    //    android.registerTransform(new MyTransform(project))
    // 注册MyTransform
    project.android.registerTransform(new MyTransform(project))

    // 创建一个Extension，名字叫做 traceConfig 里面可配置的属性参照Config
    project.extensions.create("traceConfig", Config)

    //生产一个类
    if (project.plugins.hasPlugin(AppPlugin)) {
      //获取到Extension，Extension就是 build.gradle中的{}闭包
      project.android.applicationVariants.all { variant ->
        //获取到scope,作用域
        def variantData = variant.variantData
        def scope = variantData.scope

        //拿到build.gradle中创建的Extension的值
        def config = project.extensions.getByName("traceConfig")

        //创建一个task
        def createTaskName = scope.getTaskName("CeShi", "MyTestPlugin")
        def createTask = project.task(createTaskName)
        //设置task要执行的任务
        createTask.doLast {
          //生成java类
          createJavaTest(variant, config)
        }
        //设置task依赖于生成BuildConfig的task，然后在生成BuildConfig后生成我们的类
        String generateBuildConfigTaskName = variant.getVariantData().
            getScope().
            getGenerateBuildConfigTask().name
        def generateBuildConfigTask = project.tasks.getByName(generateBuildConfigTaskName)
        if (generateBuildConfigTask) {
          createTask.dependsOn generateBuildConfigTask
          generateBuildConfigTask.finalizedBy createTask
        }
      }
    }
    System.out.println("------------------结束了吗----------------------");
  }

  static def buildTime() {
    return new Date().format("yyyy:MM:dd HH:mm")
  }

  // todo 1生成一个java类
  static void createJavaTest(variant, config) {
    //要生成的内容,fixme variant如何获取app包名
    def content = """package org.jaaksi.demo.gradle;

/**
 * create by fuchaoyang at ${buildTime()}
 */
public class MyPlguinTestClass {
  public static final String str = "${config.str}";
}
                        """;
    //获取到BuildConfig类的路径
    File outputDir = variant.getVariantData().getScope().getBuildConfigSourceOutputDir()

    def javaFile = new File(outputDir, "MyPlguinTestClass.java")

    javaFile.write(content, 'UTF-8')
  }
}
